package com.kchouse;


import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.model.LatLng;
import com.kchouse.bean.BannerItem;
import com.kchouse.bean.HostItem;
import com.kchouse.bean.MerchantItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseFragment;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.MyUtils;
import com.kchouse.common.SharedPreferencesUtil;
import com.kchouse.homepage.CityListActivity;
import com.kchouse.homepage.CouponsActivity;
import com.kchouse.homepage.DirectlyActivity;
import com.kchouse.homepage.GDMapActivity;
import com.kchouse.homepage.GoodsDetailsActivity;
import com.kchouse.homepage.MerchantsActivity;
import com.kchouse.homepage.PrestoreActivity;
import com.kchouse.homepage.RecruitmentActivity;
import com.kchouse.homepage.RescueActivity;
import com.kchouse.homepage.ToolkitActivity;
import com.kchouse.homepage.InsuranceActivity;
import com.kchouse.mine.LoginPhoneActivity;
import com.kchouse.view.BannerLoader;
import com.kchouse.common.ToastUtils;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.zaaach.toprightmenu.MenuItem;
import com.zaaach.toprightmenu.TopRightMenu;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;


/**
 * A simple {@link Fragment} subclass.
 */
public class HomepageFragment extends BaseFragment implements View.OnClickListener {


    private View view;
    private ListView lv_item;
    private LayoutInflater inflater;
    private View ll_directly;
    private Intent intent = new Intent();
    private ArrayList<BannerItem> listbanner = new ArrayList<>();
    private ArrayList<BannerItem> listhotbanner = new ArrayList<>();
    private ArrayList<HostItem> listhost = new ArrayList<>();
    private ScrollView sv_item;
    private View ll_merchants;
    private View ll_coupons;
    private View ll_toolkit;
    private View ll_rescue;
    private View citylist;
    private TextView tv_city;
    private String curcityname = "厦门";
    private View ll_insurance;
    private View ll_recruitment;
    private ImageView iv_message;
    private TopRightMenu mTopRightMenu;
    //    //添加菜单项
//    List<MenuItem> menuItems = new ArrayList<>();
    private Integer totalCount;//总页数
    private LvAdapter adapter;
    private TextView tv_addpage;
    private int page = 1;
    private boolean isLogin = false;
    private View ll_prestore;

    public HomepageFragment() {
        // Required empty public constructor
    }


    @Override
    public void onResume() {
        super.onResume();
//        sv_item.scrollTo(0, 0);

        sv_item.fullScroll(ScrollView.FOCUS_UP);//滚动到顶部

        if (!MainActivity.mobile.equals("")) {
            isLogin = true;
        } else {
            isLogin = false;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

//        page=1;
//        listhost.clear();
//        GetHotList(page);

        page = 1;
        GetHotList(page);
        if (view == null) {
            this.inflater = inflater;
            view = inflater.inflate(R.layout.fragment_homepage, null);
            intiData();
            intiView();
        }
        return view;
    }


    private void intiView() {
        sv_item = (ScrollView) view.findViewById(R.id.sv_item);
        lv_item = (ListView) view.findViewById(R.id.lv_item);
        adapter = new LvAdapter();
        lv_item.setAdapter(adapter);
        tv_addpage = (TextView) view.findViewById(R.id.tv_addpage);
        tv_addpage.setOnClickListener(this);


        lv_item.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                HostItem item = listhost.get(position);
                if (TextUtils.isEmpty(item.getMerchantId())) {
                    intent.putExtra("isDir", true);
                    intent.putExtra("id", item.getId());
                    intent.setClass(getActivity(), GoodsDetailsActivity.class);
                    startActivity(intent);
                } else {
                    intent.putExtra("isDir", false);
                    intent.putExtra("id", item.getId());
                    intent.setClass(getActivity(), GoodsDetailsActivity.class);
                    startActivity(intent);
                }


            }
        });
        ll_directly = view.findViewById(R.id.ll_directly);
        ll_directly.setOnClickListener(this);
        ll_merchants = view.findViewById(R.id.ll_merchants);
        ll_merchants.setOnClickListener(this);
        ll_coupons = view.findViewById(R.id.ll_coupons);
        ll_coupons.setOnClickListener(this);
        ll_rescue = view.findViewById(R.id.ll_rescue);
        ll_rescue.setOnClickListener(this);
        ll_toolkit = view.findViewById(R.id.ll_toolkit);
        ll_toolkit.setOnClickListener(this);
        ll_recruitment = view.findViewById(R.id.ll_recruitment);
        ll_recruitment.setOnClickListener(this);
        ll_prestore = view.findViewById(R.id.ll_prestore);
        ll_prestore.setOnClickListener(this);

        ll_insurance = view.findViewById(R.id.ll_insurance);
        ll_insurance.setOnClickListener(this);

        citylist = view.findViewById(R.id.citylist);
        citylist.setOnClickListener(this);

        tv_city = (TextView) view.findViewById(R.id.tv_city);

    }

    /**
     * 初始化热门活动banner
     */
    private void intiHotBanner() {
        Banner hot_banner = (Banner) view.findViewById(R.id.hot_banner);
        //设置banner样式
        hot_banner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        //设置图片加载器
        hot_banner.setImageLoader(new BannerLoader());
        //设置图片集合
        hot_banner.setImages(listhotbanner);
        //设置banner动画效果
        hot_banner.setBannerAnimation(Transformer.CubeOut);
        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        hot_banner.isAutoPlay(true);
        //设置轮播时间
        hot_banner.setDelayTime(4000);
        //设置指示器位置（当banner模式中有指示器时）
        hot_banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        hot_banner.start();
    }

    /**
     * 初始化首页banner
     */
    private void intiBanner() {
        Banner banner = (Banner) view.findViewById(R.id.banner);
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new BannerLoader());
        //设置图片集合
        banner.setImages(listbanner);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
//        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }

    private void intiData() {


        listbanner.clear();
        GetBanner("INDEX");
        listhotbanner.clear();
        GetBanner("ACTIVITY");
        listhost.clear();
//        page = 1;
//        GetHotList(page);

//        //当前仅支持厦门 漳州
//        mTopRightMenu = new TopRightMenu(getActivity());
//        menuItems.add(new MenuItem("厦门市"));
//        menuItems.add(new MenuItem("漳州市"));
//        mTopRightMenu.addMenuList(menuItems);
    }

    /**
     * 获取热门套餐
     */
    private void GetHotList(int page) {
        String url = API.GetHotList;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数

        params.addFormDataPart("page", page);
        params.addFormDataPart("pageSize", 10);
        params.addFormDataPart("lat", StartActivity.mLatitude + "");
        params.addFormDataPart("log", StartActivity.mLongitude + "");
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    totalCount = data.getInteger("totalCount");
                    if (listhost.size() == totalCount)//总个数已满
                    {
//                        hao_recycleview.setCanloadMore(false);
                        ToastUtils.getInstanc(getActivity()).showToast("暂无更多");
                        tv_addpage.setVisibility(View.GONE);
                    } else {
                        listhost.addAll(JSONObject.parseArray(data.getString("hotList"), HostItem.class));
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(getActivity()).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }
            //请求网络结束

            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    /**
     * 获取banner
     *
     * @param typebanner INDEX 首页、 UNION 联盟 、SHOP 商家列表 、ACTIVITY 热门活动
     */
    private void GetBanner(final String typebanner) {
        String url = API.GetBanner;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数

//        JSONObject ob = new JSONObject();
//        ob.put("type", typebanner);
        params.addFormDataPart("type", typebanner);
//        ob.put("captcha", code);
//        params.addFormDataPart("file", file);//上传单个文件
//        params.addFormDataPart("files", files);//上传多个文件
//        params.addHeader("token", token);//添加header信息
//        params.applicationJson(ob);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    switch (typebanner) {
                        case "INDEX":
                            listbanner.addAll(JSONObject.parseArray(datastr, BannerItem.class));
                            intiBanner();
                            break;
                        case "ACTIVITY":
                            listhotbanner.addAll(JSONObject.parseArray(datastr, BannerItem.class));
                            intiHotBanner();
                            break;
                    }

                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(getActivity()).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.ll_directly://平台直营
                intent.setClass(getActivity(), DirectlyActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_merchants://商家优惠
                intent.setClass(getActivity(), MerchantsActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_coupons://优惠券
//                if (checkLogin()) return;
                intent.setClass(getActivity(), CouponsActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_rescue://一键施救
                intent.setClass(getActivity(), RescueActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_toolkit://工具箱
                intent.setClass(getActivity(), ToolkitActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_recruitment://汽车招聘

                intent.setClass(getActivity(), RecruitmentActivity.class);
//                intent.setClass(getActivity(),SeccarActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_insurance://汽车保险
                intent.setClass(getActivity(), InsuranceActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_prestore://预存活动
                intent.setClass(getActivity(), PrestoreActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_location://高德地图（切换定位）隐藏
                intent.setClass(getActivity(), GDMapActivity.class);
                startActivity(intent);
                break;

            case R.id.citylist://切换城市
                intent.setClass(getActivity(), CityListActivity.class);
                startActivityForResult(intent, 0);
//                intiCity();
                break;
            case R.id.tv_addpage://翻页
                page = page + 1;
                GetHotList(page);
                break;


        }
    }

    /**
     * 控件下方弹出（暂时不用）
     * 切换城市显示菜单
     */
    private void intiCity() {
//        mTopRightMenu
//                .setHeight(LinearLayout.LayoutParams.WRAP_CONTENT)     //默认高度480
////                        .setWidth(320)      //默认宽度wrap_content
//                .showIcon(false)     //显示菜单图标，默认为true
//                .dimBackground(true)        //背景变暗，默认为true
//                .needAnimationStyle(true)   //显示动画，默认为true
//                .setAnimationStyle(R.style.TRM_ANIM_STYLE)
//                .setOnMenuItemClickListener(new TopRightMenu.OnMenuItemClickListener() {
//                    @Override
//                    public void onMenuItemClick(int position) {
////                        Toast.makeText(getActivity(), "点击菜单:" + position, Toast.LENGTH_SHORT).show();
//                        curcityname = menuItems.get(position).getText();
//                        tv_city.setText(curcityname);
//                    }
//                })
////                        .showAsDropDown(moreBtn, -225, 0);	//带偏移量
//                .showAsDropDown(citylist);
    }

    class LvAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return listhost.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            HostItem item = listhost.get(position);
            View view = null;
//            if (item.getPublishType().equals("UNION"))//是否联盟
            if (TextUtils.isEmpty(item.getMerchantId()))//是否联盟
            {
                view = getLayoutInflater().inflate(R.layout.lv_directly_item, null);
                TextView tv_pt = (TextView) view.findViewById(R.id.tv_pt);
                tv_pt.setVisibility(View.VISIBLE);
                TextView tv_original = (TextView) view.findViewById(R.id.tv_original);
//                tv_original.setText(MyUtils.getdouble(item.getOriginalPrice()));
                tv_original.setText(item.getOriginalPrice()+"");
                tv_original.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//添加下划线
                ImageView iv_item = (ImageView) view.findViewById(R.id.iv_item);
                Picasso.with(getActivity()).load(item.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_item);
                TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
//                tv_price.setText(MyUtils.getdouble(item.getPrice()));
                tv_price.setText(item.getPrice()+"");
                TextView tv_sales = (TextView) view.findViewById(R.id.tv_sales);
                tv_sales.setText("销量：" + (item.getSales() + item.getRealSales()));
                TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
                tv_title.setText(item.getName());
                TextView tv_giving = (TextView) view.findViewById(R.id.tv_giving);
                if (item.getCouponLimit() == 0) {
                    tv_giving.setText("");
                } else {
                    tv_giving.setText("最高抵扣" + (item.getCouponLimit() * 10) + "元");
                }
            } else {
                view = inflater.inflate(R.layout.lv_home_item, null);
                TextView tv_original = (TextView) view.findViewById(R.id.tv_original);
//                tv_original.setText(MyUtils.getdouble(item.getOriginaolPrice()));
                tv_original.setText(item.getOriginalPrice()+"");
                tv_original.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//添加下划线
                ImageView iv_item = (ImageView) view.findViewById(R.id.iv_item);
                Picasso.with(getActivity()).load(item.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_item);
                TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
//                tv_price.setText(MyUtils.getdouble(item.getPrice()));
                tv_price.setText(item.getPrice()+"");
                TextView tv_sales = (TextView) view.findViewById(R.id.tv_sales);
                tv_sales.setText("销量：" + (item.getSales() + item.getRealSales()));
                TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
                tv_title.setText(item.getName());
                TextView tv_giving = (TextView) view.findViewById(R.id.tv_giving);

                if (item.getCouponLimit() == 0) {
                    tv_giving.setText("");
                } else {
                    tv_giving.setText("最高抵扣" + (item.getCouponLimit() * 10) + "元");
                }
                TextView tv_merchantName = (TextView) view.findViewById(R.id.tv_merchantName);
                tv_merchantName.setText(item.getMerchantShortName());
                if (item.isFollowStatus()) {
                    tv_merchantName.setTextColor(getResources().getColor(R.color.text_main));
                    tv_merchantName.setTypeface(Typeface.DEFAULT_BOLD);

                } else {
                    tv_merchantName.setTypeface(Typeface.DEFAULT);
                    tv_merchantName.setTextColor(getResources().getColor(R.color.colorblack));
                }
                TextView tv_distance = (TextView) view.findViewById(R.id.tv_distance);
                double distance = item.getDistance() / 1000;
                DecimalFormat df = new DecimalFormat("0.##");
                String st = df.format(distance);
                tv_distance.setText(st + "km");
//                intiDistance(tv_distance, item);
            }
            return view;
        }
    }

    /**
     * 距离计算
     *
     * @param
     * @param item
     */
    private void intiDistance(TextView tv, HostItem item) {
        LatLng startLatlng = new LatLng(StartActivity.mLatitude, StartActivity.mLongitude);
        LatLng endLatlng = new LatLng(Double.valueOf(item.getLatitude()), Double.valueOf(item.getLongitude()));

        double distance = AMapUtils.calculateLineDistance(startLatlng, endLatlng);
        distance = distance / 1000;
        DecimalFormat df = new DecimalFormat("0.##");
        String st = df.format(distance);
        tv.setText(st + "km");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data != null) {
            if (!TextUtils.isEmpty(data.getStringExtra("cityname"))) {
                curcityname = data.getStringExtra("cityname");
                tv_city.setText(curcityname);
            }
        }
    }

    /**
     * 校验登录状态
     *
     * @return
     */
    private boolean checkLogin() {
        // 如果未登录都进入登录界面
        if (!isLogin) {
            intent.setClass(getActivity(), LoginPhoneActivity.class);
            startActivity(intent);
            return true;
        }
        return false;
    }

    @Override
    public void onStart() {
        super.onStart();
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("refresh");
        //注册广播
        getActivity().registerReceiver(new MyReceiver(), myIntentFilter);
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            listhost.clear();
            page = 1;
            GetHotList(page);
        }
    }


}
